//
//  DataManager.m
//  MoRan
//
//  Created by MoRan  on 2023.
//  Copyright © 2023 MoRan . All rights reserved.
//

#import "DataManager.h"

@interface DataManager ()

@property (nonatomic, strong) YTKKeyValueStore *store;

@end

@implementation DataManager

+ (instancetype)shareInstance {
    static DataManager *_manager = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _manager = [[self alloc] init];
    });
    return _manager;
}

#pragma mark - 公共数据

//获取随机guid guid一般是32位的，生成规则和随机数不同
- (NSString*)getGuid {
    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
    CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);
    CFRelease(uuid_ref);
    NSString *uuid = [NSString stringWithString:(__bridge NSString*)uuid_string_ref];
    CFRelease(uuid_string_ref);
    return [uuid stringByReplacingOccurrencesOfString:@"-" withString:@""];
}

- (NSArray *)tableAry {
    return @[@"notification"];
}

#pragma mark - 初始化

- (void)initTable {
    if (![[[NSUserDefaults standardUserDefaults] objectForKey:@"isSecond"] boolValue]) {
        //第一次
        [self.tableAry enumerateObjectsUsingBlock:^(NSString *name, NSUInteger idx, BOOL * _Nonnull stop) {
            //创建表
            [self.store createTableWithName:[NSString stringWithFormat:@"%@_table",name]];
        }];
        
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:@"YES" forKey:@"isSecond"];
        [userDefaults synchronize];
    }
}

#pragma mark - 添加数据

- (void)addNotificationDataWithModel:(MRNotificationModel *)model {
    if (model) {
        NSString *notificationId = [self getGuid];
        if (model.notificationId.length > 0) {
            notificationId = model.notificationId;
        }
        model.notificationId = notificationId;
    
        NSDictionary *dic = model.mj_keyValues;
        [self.store putObject:dic withId:notificationId intoTable:[NSString stringWithFormat:@"%@_table",@"notification"]];
    }
}

#pragma mark - 查询数据

//获取所有数据
- (NSArray *)getNotificationArrayWithIndex:(NSInteger)index {
    NSArray *array = [self.store getAllItemsFromTable:[NSString stringWithFormat:@"%@_table",@"notification"]];
    //排序
    NSArray *sortArray = [array sortedArrayUsingComparator:^NSComparisonResult(YTKKeyValueItem *item1, YTKKeyValueItem *item2) {
        
        //时间
        //用于格式化NSDate对象
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //设置格式：zzz表示时区
        [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];

        //NSDate转NSString
        NSString *createdTime1 = [dateFormatter stringFromDate:item1.createdTime];
        NSInteger year1 = [createdTime1 integerValue];

        
        //NSDate转NSString
        NSString *createdTime2 = [dateFormatter stringFromDate:item2.createdTime];
        NSInteger year2 = [createdTime2 integerValue];

        if (year1 > year2) { //不使用intValue比较无效
            return NSOrderedAscending;
        } else if (year1 < year2) {
            return NSOrderedDescending;
        } else {
            return NSOrderedSame;//相等
        }
    }];
    
    NSMutableArray *modelAry = [NSMutableArray arrayWithCapacity:10];
    [sortArray enumerateObjectsUsingBlock:^(YTKKeyValueItem *item, NSUInteger idx, BOOL * _Nonnull stop) {
        MRNotificationModel *model = [MRNotificationModel mj_objectWithKeyValues:item.itemObject];
        
        //时间
        //用于格式化NSDate对象
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //设置格式：zzz表示时区
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        //NSDate转NSString
        NSDate *date = [dateFormatter dateFromString:model.time];
        //设置格式：zzz表示时区
        [dateFormatter setDateFormat:@"yyyyMMddHHmm"];
        //NSDate转NSString
        NSString *createdTime2 = [dateFormatter stringFromDate:[NSDate date]];
        NSInteger time2 = [createdTime2 integerValue];
        //NSDate转NSString
        NSString *createdTime1 = [dateFormatter stringFromDate:date];
        NSInteger time1 = [createdTime1 integerValue];

        if (index == 0) {
            if (time1 >= time2) {
                [modelAry addObject:model];
            }
        } else {
            if (time1 < time2) {
                [modelAry addObject:model];
            }
        }
    }];
    return modelAry;
}

#pragma mark - 删除

//删除指定id数据
- (void)deleteNotificationDataDicWithNotificationId:(NSString *)notificationId {
    NSArray *array = [self.store getAllItemsFromTable:[NSString stringWithFormat:@"%@_table",@"notification"]];
    
    __block MRNotificationModel *data = nil;
    
    [array enumerateObjectsUsingBlock:^(YTKKeyValueItem *item, NSUInteger idx, BOOL * _Nonnull stop) {
        MRNotificationModel *model = [MRNotificationModel mj_objectWithKeyValues:item.itemObject];
        if ([notificationId isEqualToString:model.notificationId]) {
            data = model;
        }
    }];
    
    if (data) {
        [self.store deleteObjectById:data.notificationId fromTable:[NSString stringWithFormat:@"%@_table",@"notification"]];
    }
}

#pragma mark - 懒加载

- (YTKKeyValueStore *)store {
    if (!_store) {
        _store = [[YTKKeyValueStore alloc] initDBWithName:[NSString stringWithFormat:@"%@.db",@"MoRan"]];
    }
    return _store;
}

@end
